package com.example.productserver.service.impl;

import com.example.productserver.entity.CyGoods;
import com.example.productserver.exception.CustomException;
import com.example.productserver.mapper.CyGoodsMapper;
import com.example.productserver.result.ResultData;
import com.example.productserver.result.ResultUtil;
import com.example.productserver.service.CyGoodsService;
import com.example.productserver.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class CyGoodsServiceImpl implements CyGoodsService {

    @Autowired
    private CyGoodsMapper cyGoodsMapper;


    @Override
    public ResultData<CyGoods> getCyGoodsInfo(Integer id) {
        Example exampleCyGoods=new Example(CyGoods.class);
        exampleCyGoods.createCriteria().andEqualTo("id",id).andEqualTo("isSale",1);
        List<CyGoods> cyGoods = cyGoodsMapper.selectByExample(exampleCyGoods);
        if(CollectionUtils.isEmpty(cyGoods)){
           throw new CustomException("此商品不存在或者未上架");
        }
        CyGoods cyGoodsData = cyGoods.get(0);
        return ResultUtil.getResultData(cyGoodsData);
    }

    @Override
    public ResultData<List<Integer>> getAllCyGoodsIds() {

        Example exampleCyGoods=new Example(CyGoods.class);
        List<CyGoods> cyGoods = cyGoodsMapper.selectByExample(exampleCyGoods);
        if(CollectionUtils.isEmpty(cyGoods)){
            throw new CustomException("没有任何商品");
        }
        List<Integer> pids = cyGoods.stream().map(CyGoods::getId).collect(Collectors.toList());
        return ResultUtil.getResultData(pids);
    }
}
